package Aleehot100;

/**
 * ClassName: c024
 * Package: Aleehot100
 * Description: 回文链表
 *
 * @Author BCXJ
 * @Create 2025/6/13 10:02
 * @Version 1.0
 * @Since 1.0
 */
public class c024 {
    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(0);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(0);
        ListNode listNode6 = new ListNode(1);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;
        listNode5.next = listNode6;
        System.out.println(isPalindrome(listNode1));
    }
    static class ListNode {
        int val;
        ListNode next;
        public ListNode(int val) {
            this.val = val;
            next = null;
        }
    }
    public static boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null) {
            return true;
        }

        // 快慢指针
        ListNode fast = head, slow = head;
        while(fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        // 反转slow后面的链表
        ListNode pre = null, cur = slow, next;
        while(cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        // pre即为最后一个节点
        ListNode h2 = head, tail = pre;
        boolean res = true;
        while(h2 != null && tail != null) {
            if(h2.val != tail.val) {
                res = false;
                break;
            }
            h2 = h2.next;
            tail = tail.next;
        }

        // 恢复链表
        cur = pre;
        pre = null;
        while(cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return res;
    }
}
